package com.nariano.server.services.userservice.impl;

import java.util.List;
import java.util.Set;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Expression;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.nariano.server.domain.entities.User;
import com.nariano.server.services.userservice.UserService;

@Transactional
public class UserServiceImpl implements UserService {
    
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    
    private volatile int  nofUser = -1;

    public User findUserFromEmail(String email) {
        DetachedCriteria dc = DetachedCriteria.forClass(User.class);
        dc.add(Expression.eq("email", email));
        List list = getHibernateTemplate().findByCriteria(dc);
        if (list.isEmpty()) { return null; }
        Assert.isTrue(1 == list.size(), "Java datamodel not compliant with db-model: " + list);
        return (User) (list.isEmpty()? null : list.get(0));
    }

    public User findUserFromUserName(String userName) {
        DetachedCriteria dc = DetachedCriteria.forClass(User.class);
        dc.add(Expression.eq("userName", userName));
        List list = getHibernateTemplate().findByCriteria(dc);
        if (list.isEmpty()) { return null; }
        Assert.isTrue(1 == list.size(), "Java datamodel not compliant with db-model: " + list.size());
        return (User) (list.isEmpty()? null : list.get(0));
    }

    public void deleteUser(User user) {
        HibernateTemplate ht = getHibernateTemplate();
        ht.delete(user);
        nofUser--;
    }

    

    public User insertUser(User user) {
        HibernateTemplate ht = getHibernateTemplate();
        Integer id = (Integer) ht.save(user);
        user.setId(id);
        nofUser++;
        return user;
    }

    public void updateUser(User user) {
        HibernateTemplate ht = getHibernateTemplate();
        ht.update(user);
    }
    
    public List<User> getAllUsers() {
        List list = getHibernateTemplate().loadAll(User.class);
        return list;
    }
    
    private HibernateTemplate getHibernateTemplate() {
        return new HibernateTemplate(sessionFactory);
    }

    
	@Override
	public int getNofUsers() {
		// TODO replace with named query Population.count
		if (nofUser == -1) {
			nofUser = getHibernateTemplate().loadAll(User.class).size();
		}	
		return nofUser;
	}

	@Override
	public User findUserFromId(Integer id) {
		throw new UnsupportedOperationException("Implement please!");
	}

	@Override
	public List<User> findAttackers(Integer id) {
		throw new UnsupportedOperationException("Implement please!");
	}

   
}
